//
//  CollectionViewController.m
//  miaopai
//  Created by 杜昕宇 on 15/11/18.
//  Copyright © 2015年 Crow Zhang. All rights reserved.

#import "CollectionViewController.h"
#import "CoreData.h"
#import "MacroDefinition.h"
#import "CollectionJoke.h"
#import "JokeTableViewCell.h"
#import "PicTableViewCell.h"
#import "UMSocial.h"

@interface CollectionViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, retain) UISegmentedControl *segment;//segment

@property (nonatomic, retain) CoreData *coreDataManager; // coredata

//    段子界面 以及数组
@property (nonatomic, retain) UIView *jokeView; // 段子后面的背景图

@property (nonatomic, retain) UITableView *jokeTableView; // 段子 tableview

@property (nonatomic, retain) NSMutableArray *jokeArray; // 段子 数组

@property (nonatomic, retain) UILabel *jokePlaceLabel;

//    图片界面 以及数组
@property (nonatomic, retain) UIView *picView; // 图片后面的背景图

@property (nonatomic, retain) UITableView *picTableView; // 图片 tableview

@property (nonatomic, retain) NSMutableArray *picArray; // 图片数组

@property (nonatomic, retain) UILabel *picPlaceLabel;
@end

@implementation CollectionViewController


//    初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.coreDataManager = [CoreData shareManagerWithFile:@"joke"]; // coredata 初始化
        self.picArray = [[NSMutableArray alloc] init]; // 数组初始化
        self.jokeArray = [[NSMutableArray alloc] init]; // 数组初始化


//        此处数据库解析
        [self getPicData]; // 图片
        [self getJokeData]; // 段子
}
    return self;
}

#pragma mark 获得图片的数组
- (void)getPicData{ // 图片
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"CollectionPicture"];
    NSArray *array = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    [self.picArray addObjectsFromArray:array];
}

#pragma mark 获得段子的数组
- (void)getJokeData{ // 段子
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"CollectionJoke"];
    NSArray *array = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    [self.jokeArray addObjectsFromArray:array];
}

- (void)dealloc{
    [_picView release];
    [_jokeView release];
    [_segment release];
    [_coreDataManager release];
    [_jokeArray release];
    [_jokeTableView release];
    [_picArray release];
    [_picTableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];

    [self creatViews]; // 创建视图
}

- (void)creatViews {

//    segment
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@" 段  子 ", @" 图  片 "]];
    self.segment.selectedSegmentIndex = 0;
    [_segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = _segment;
    [_segment release];

    /**********************************图片************************************/
    self.picView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.picView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_picView];
    [_picView release];

    self.picTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _picView.Width, _picView.Height) style:UITableViewStylePlain];
    self.picTableView.delegate = self;
    self.picTableView.dataSource = self;
    self.picTableView.tableFooterView = [[[UIView alloc] init] autorelease];
    [_picView addSubview:_picTableView];
    [_picTableView release];

    self.picPlaceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 11, _picView.Width , 20)];
    self.picPlaceLabel.text = @"还没有收藏, 快去收藏一个吧 ~";
    self.picPlaceLabel.textColor = [UIColor colorWithRed:0.5709 green:0.5709 blue:0.5709 alpha:1.0];
    self.picPlaceLabel.textAlignment = NSTextAlignmentCenter;
    _picPlaceLabel.hidden = YES;
    [_picView addSubview:self.picPlaceLabel];
    [_picPlaceLabel release];
/*********************************段子*******************************/
    self.jokeView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.jokeView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_jokeView];
    [_jokeView release];

    self.jokeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _jokeView.Width, _jokeView.Height) style:UITableViewStylePlain];
    self.jokeView.backgroundColor = [UIColor blackColor];
    self.jokeTableView.tableFooterView = [[[UIView alloc] init] autorelease];
    self.jokeTableView.delegate = self;
    self.jokeTableView.dataSource = self;
    [self.jokeView addSubview:_jokeTableView];
    [_jokeTableView release];

    self.jokePlaceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 11, _jokeView.Width , 20)];
    self.jokePlaceLabel.text = @"还没有收藏, 快去收藏一个吧 ~";
    self.jokePlaceLabel.textAlignment = NSTextAlignmentCenter;
    self.jokePlaceLabel.textColor = [UIColor colorWithRed:0.5709 green:0.5709 blue:0.5709 alpha:1.0];
    _jokePlaceLabel.hidden = YES;
    [_jokeTableView addSubview:_jokePlaceLabel];
    [_jokePlaceLabel release];

}
//    segment 点击事件
- (void)segmentAction:(UISegmentedControl *)segment{
    if (segment.selectedSegmentIndex == 0) {
        [self.view insertSubview:_jokeView aboveSubview:_picView];
        return;
    }
    [self.view insertSubview:_picView aboveSubview:_jokeView];
}

#pragma mark - 协议 
#pragma mark 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    CGFloat vHeight = SCREEN_HEIGHT / 20;

    if (tableView == _jokeTableView) {
        CollectionJoke *joke = [self.jokeArray objectAtIndex:indexPath.row];
        CGFloat height = [JokeTableViewCell heightOfText:joke.text];
        return height + 2 * vHeight + 10;
    } else if (tableView == _picTableView) {

        CGFloat vHeight = SCREEN_HEIGHT / 20;
        CGFloat imageHeight = SCREEN_HEIGHT / 30;

            CollectionPicture *pic = [self.picArray objectAtIndex:indexPath.row];
            BOOL Screen_width = [pic.width floatValue] < (SCREEN_WIDTH - 20) ? YES : NO;
            if (Screen_width) {
                CGFloat height = vHeight + 5 + [PicTableViewCell heightOfText:pic.text] + [pic.height floatValue] + imageHeight + 15;
                return height;
            }
            CGFloat width = [pic.width floatValue] / SCREEN_WIDTH;
            //    CGFloat height = [pic.height floatValue] / width;
            CGFloat height = vHeight + 5 + [PicTableViewCell heightOfText:pic.text] + [pic.height floatValue] / width + imageHeight + 15;
        return height;
    }

    return 200;
}

#pragma mark 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.jokeTableView) {

        BOOL judge = _jokeArray.count == 0 ? NO : YES;
        self.jokePlaceLabel.hidden = judge;
        return _jokeArray.count;
    } else if (tableView == _picTableView) {
        BOOL judge = _picArray.count == 0 ? NO : YES;
        self.picPlaceLabel.hidden = judge;
        return _picArray.count;
    }
    return 1;
}
#pragma mark 内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.jokeTableView == tableView) {
        JokeTableViewCell *cell = [JokeTableViewCell JokeTableView:tableView];
        CollectionJoke *joke =  [self.jokeArray objectAtIndex:indexPath.row];
        [cell classButtonClicked:^{
            [_coreDataManager.managedObjectContext deleteObject:joke];
            [self.jokeArray removeObjectAtIndex:indexPath.row];
            [_coreDataManager saveContext];

            [_jokeTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
            [_jokeTableView reloadData];
        }];

        [cell shareButtonClicked:^{
//            [UMSocialSnsService presentSnsController:self appKey:@"565415bfe0f55aaf68000909" shareText:@"" shareImage:@"" shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,nil] delegate:NULL];
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"56554e9967e58e6ff800226b"
                                              shareText:joke.text
                                             shareImage:nil
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                               delegate:nil];
        }];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.myJoke = joke;
        return cell;
    } else if (tableView == _picTableView) {
        PicTableViewCell *cell = [PicTableViewCell PicTableView:tableView];
        CollectionPicture *picture = [self.picArray objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.picture =picture;
        [cell classButtonClicked:^{
            [_coreDataManager.managedObjectContext deleteObject:picture];
            [_picArray removeObjectAtIndex:indexPath.row];
            [_coreDataManager saveContext];

            [_picTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
            [_picTableView reloadData];
        }];

        [cell shareButtonClicked:^{
//            [UMSocialSnsService presentSnsController:self appKey:@"565415bfe0f55aaf68000909" shareText:@"" shareImage:@"" shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,nil] delegate:NULL];
            [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:picture.original];
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"56554e9967e58e6ff800226b"
                                              shareText:@"发现了一张好图"
                                             shareImage:nil
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                               delegate:nil];
        }];
        return cell;
    }

#if 1
//    默认状态
    static NSString *cellIdentify = @"cellIdnetfy";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    CollectionJoke *joke = [self.jokeArray objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor orangeColor];
    cell.textLabel.text = joke.text;
    return cell;
#endif
}

/**
 *  返回根据参数的到的数据库数组
 *
 *  @param tableName 表名
 *  @param str        text 的内容, 用于索引
 *
 *  @return 索引得到的数组
 */
- (NSArray *)returnArrayWithTable:(NSString *)tableName andText:(NSString *)str {
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:tableName inManagedObjectContext:_coreDataManager.managedObjectContext];
    [request setEntity:entity];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"text = '%@'", str]];
    NSArray *arr = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    return arr;
}


#pragma mark 可以被编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

#pragma mark 编辑模式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

#pragma mark 编辑实现
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _jokeTableView) {
        CollectionJoke *joke = [_jokeArray objectAtIndex:indexPath.row];
        [_coreDataManager.managedObjectContext deleteObject:joke];
        [_jokeArray removeObjectAtIndex:indexPath.row];
        [_coreDataManager saveContext];
        
        [_jokeTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
        [_jokeTableView reloadData];
    } else if (tableView == _picTableView) {
        CollectionPicture *pic = [_picArray objectAtIndex:indexPath.row];
        [_coreDataManager.managedObjectContext deleteObject:pic];
        [_picArray removeObjectAtIndex:indexPath.row];
        [_coreDataManager saveContext];

        [_picTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
        [_picTableView reloadData];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    UIView * view = [self.tabBarController.view.subviews lastObject];
    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(0, kHeight + 100, kWidth, 48);
    }];

    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
}

@end
